package wx.wechat.api;

import javax.servlet.http.HttpServletRequest;

public class API {

    /**
     * @return 返回解析后的IP地址
     * @function 获取客户端请求的IP地址
     */
    protected String getClientIp() {

        return "127.0.0.1";
    }

    private static final String[] IP_HEADER_CANDIDATES = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR" };

    public static String getClientIpAddress(HttpServletRequest request) {
        String ip = null;
        for (String header : IP_HEADER_CANDIDATES) {
            ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                if("0:0:0:0:0:0:0:1".equals(ip)){
                    ip = "127.0.0.1";
                }
                return ip;
            }
        }
        ip = request.getRemoteAddr();

        if("0:0:0:0:0:0:0:1".equals(ip)){
            ip = "127.0.0.1";
        }
        ip = ip.split(",")[0];
        return ip;
    }
}
